package com.hup.minicontroller.client.presenter;

import com.hup.minicontroller.client.model.AppConfig;
import com.hup.minicontroller.client.model.AppState;
import com.hup.minicontroller.client.mvp.IClientHandler;
import com.hup.minicontroller.client.mvp.IClientHandler.ClientHandlerList;
import com.hup.minicontroller.client.mvp.MainMvp.MainPresenter;
import com.hup.minicontroller.client.service.LanBroadcastReceiverService;
import com.hup.minicontroller.client.view.main.MainFrame;
import com.hup.minicontroller.common.SubThreadHandler;
import com.hup.utils.commons.start.SimpleExitHandler;
import com.hup.utils.commons.start.SpringContext;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

/**
 * @author hugan
 * @date 2021/5/23
 */
@Log4j2
@Component
public class MainPresenterImpl implements MainPresenter {

    public MainPresenterImpl() {
        SpringContext.getBean(SimpleExitHandler.class).setExitAction(this::doExit);
    }

    @Override
    public void startUp() {
        AppConfig appConfig = SpringContext.getBean(AppState.class).getAppConfig().loadFromFile();//加载配置
        log.info("appConfig={}", appConfig);
        SpringContext.getBean(MainFrame.class).initConfig().setVisible(true);
        SpringContext.executeIfExist(LanBroadcastReceiverService.class, s -> s.switchService(true));
    }

    private void doExit() {
        log.info("");
        SubThreadHandler subThreadHandler = SpringContext.getBean(SubThreadHandler.class);
        subThreadHandler.execute(() -> SpringContext.executeForeach(ClientHandlerList.class, IClientHandler::doTerminate));
        subThreadHandler.execute(() -> SpringContext.executeIfExist(LanBroadcastReceiverService.class, LanBroadcastReceiverService::doTerminate));
        subThreadHandler.schedule(() -> {
            log.info("马上会执行exit");
            System.exit(0);
        }, 500);
    }

}
